/*
 * File     : EnumBitFieldHelperImpl.java
 * Created  : 1 Jan 2012
 *
 * Copyright © 2012 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal;

import com.googlecode.dni.type.cenum.EnumBitFieldHelper;

/**
 * <p>
 *  Implementation of {@link EnumBitFieldHelper}.
 * </p>
 *
 * @param <E>
 *            the enum type
 *
 * @author Matthew Wilson
 */
final class EnumBitFieldHelperImpl< E extends Enum< E > > implements EnumBitFieldHelper< E >
{

    private final EnumDictionary dictionary;

    private final int invMask;

    private final int offset;

    /**
     * @param type
     *            the type
     * @param mask
     *            the mask
     * @param offset
     *            the offset
     */
    EnumBitFieldHelperImpl( final Class< E > type,
                            final int mask,
                            final int offset )
    {
        this.invMask = ~mask;
        this.offset = offset;
        this.dictionary = EnumDictionary.get( type );
    }

    /** {@inheritDoc} */
    @Override
    public int with( final int field, final E enumValue )
    {
        int value = this.dictionary.valueForEnum( enumValue ) << this.offset;
        assert ok( value );
        return ( field & this.invMask ) | value;
    }

    /** {@inheritDoc} */
    @Override
    public E get( final int field )
    {
        int value = ( field & ~this.invMask ) >>> this.offset;
        @SuppressWarnings( "unchecked" )
        E enumValue = (E) this.dictionary.enumForValue( value );
        return enumValue;
    }

    /** {@inheritDoc} */
    @Override
    public String toString( final int field )
    {
        int value = ( field & ~this.invMask ) >>> this.offset;
        Enum< ? > enumValue = this.dictionary.enumForValue( value );
        return value + "=" + enumValue;
    }

    private boolean ok( final int value )
    {
        assert ( value & ~this.invMask ) == 0 : "Bad enum value " + Integer.toHexString( value ) + " for mask " + Integer.toHexString( ~this.invMask );
        return true;
    }

}
